/**
 * 工具类型
 */
const moment = require('moment')
const util = class util {

    formatterDateNotUTC(date) {
        return moment(date).format('YYYY-MM-DD');
    }

    formatterDate(date) {
        return moment(date).utc().format('YYYY-MM-DD');
    }

    formatterDateTime(date) {
        return moment(date).utc().format('YYYY-MM-DD HH:mm:ss');
    }

    formatterDateTimeNotUTC(date) {
        return moment(date).format('YYYY-MM-DD HH:mm:ss');
    }

    formatterTime(date) {
        return moment(date).utc().format('HH:mm:ss');
    }

    formatterTimeNotUTC(date) {
        return moment(date).format('HH:mm:ss');
    }

    formatterHM(date) {
        return moment(date).utc().format('HH:mm');
    }

    formatterHMNotUTC(date) {
        return moment(date).format('HH:mm');
    }

    loadStartTimeStr(min) {
        var nowDate = Date.now();
        var hour = moment(nowDate).format('HH');
        var hourNum = parseInt(hour);
        var startTime = hourNum > min ? hourNum : min;
        return startTime > 10 ? startTime + ':00' : '0'+startTime+':00';
    }

    loadEndTimeStr(min) {
        var nowDate = Date.now();
        var hour = moment(nowDate).format('HH');
        var hourNum = parseInt(hour);
        var startTime = (hourNum > min ? hourNum : min) + 1;
        return startTime > 10 ? startTime + ':00' : '0'+startTime+':00';
    }

    loadMinHour(min) {
        var nowDate = Date.now();
        var hour = moment(nowDate).format('HH');
        var hourNum = parseInt(hour);
        return hourNum > min ? hourNum : min;
    }

    ages(str) {
        if(str != null && str != undefined && str != '') {
            var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
            if (r == null) return 0;
            var d = new Date(r[1], r[3] - 1, r[4]);
            if (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d.getDate() == r[4]) {
                var Y = new Date().getFullYear();
                return ("" + (Y - r[1]));
            }
        }
        return 0;
    }

    /**
     * 验证手机号码是否合规
     * @param phone
     * @returns {*}
     */
    validatePhone(phone) {
        //手机号正则
        var phoneReg = /(^1[3|4|5|7|8|9]\d{9}$)|(^09\d{8}$)/;
        //电话
        if (!phoneReg.test(phone)) {
            return {
                success: false,
                message: '请输入有效的手机号码!'
            }
        } else {
            return {
                success: true
            }
        }
    }

    /**
     * 验证邮箱地址是否合规
     * @param email
     * @returns {*}
     */
    validateEmail(email) {
        var reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
        if (!reg.test(email)) {
            return {
                success: false,
                message: '请输入有效的邮箱地址!'
            }
        } else {
            return {
                success: true
            }
        }
    }


    /**
     * 浅拷贝
     * @param obj
     * @returns {{}}
     */
    copy(obj) {
        var newobj = {};
        for (var attr in obj) {
            newobj[attr] = obj[attr];
        }
        return newobj;
    }

    /**
     * 深拷贝
     * @param obj
     * @returns {*}
     */
    deepCopy(obj) {
        if (typeof obj != 'object') {
            return obj;
        }
        var newobj = {};
        for (var attr in obj) {
            newobj[attr] = this.deepCopy(obj[attr]);
        }
        return newobj;
    }

    timeDifference(dateStr) {
        //var nowDate = new Date();
        var nowDate = Date.now();
        var startDate = Date.parse(new Date(dateStr.replace(/-/g, '/')));
        var date3 = nowDate - startDate;
        //console.info(nowDate + '-' + startDate + '=' +date3);
        //计算出相差天数
        var days = Math.floor(date3 / (24 * 3600 * 1000))

        //计算出小时数
        var year = parseInt(days / 365);
        var month = parseInt(days / 30);
        var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
        //return " 相差 "+ year + "年" + month + "月" + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒";
        if (year > 0) {
            return year + '年前';
        } else if (month > 0) {
            return month + '月前'
        } else if (days > 0) {
            return days + '天前';
        } else if (hours > 0) {
            return hours + '小时前';
        } else if (minutes > 0) {
            return minutes + '分钟前';
        } else if (seconds > 0) {
            return seconds + '秒前'
        } else {
            return '现在'
        }
    }

    timeDifference2(dateStr) {
        //var nowDate = new Date();
        var nowDate = Date.now();
        var startDate = Date.parse(new Date(dateStr.replace(/-/g, '/')));
        var date3 = nowDate - startDate;
        //console.info(nowDate + '-' + startDate + '=' +date3);
        //计算出相差天数
        var days = Math.floor(date3 / (24 * 3600 * 1000))

        //计算出小时数
        var year = parseInt(days / 365);
        var month = parseInt(days / 30);
        var leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
        //return " 相差 "+ year + "年" + month + "月" + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒";
        if (year > 0) {
            return year + '年';
        } else if (month > 0) {
            return month + '个月'
        } else if (days > 0) {
            return days + '天';
        } else if (hours > 0) {
            return hours + '小时';
        } else if (minutes > 0) {
            return minutes + '分钟';
        } else if (seconds > 0) {
            return seconds + '秒'
        } else {
            return '刚来'
        }
    }

    compress(fileObj, callback) {
        var self = this;
        try {
            const image = new Image()
            image.src = URL.createObjectURL(fileObj)
            image.onload = function () {
                const that = this
                // 默认按比例压缩
                let w = that.width
                let h = that.height
                const scale = w / h
                w = fileObj.width || w
                h = fileObj.height || (w / scale)
                let quality = 0.7 // 默认图片质量为0.7
                // 生成canvas
                const canvas = document.createElement('canvas')
                const ctx = canvas.getContext('2d')
                // 创建属性节点
                const anw = document.createAttribute('width')
                anw.nodeValue = w
                const anh = document.createAttribute('height')
                anh.nodeValue = h
                canvas.setAttributeNode(anw)
                canvas.setAttributeNode(anh)
                ctx.drawImage(that, 0, 0, w, h)
                // 图像质量
                if (fileObj.quality && fileObj.quality <= 1 && fileObj.quality > 0) {
                    quality = fileObj.quality
                }
                // quality值越小，所绘制出的图像越模糊
                const data = canvas.toDataURL('image/jpeg', quality)
                // 压缩完成执行回调
                const newFile = self.convertBase64UrlToFile(data, fileObj.name, fileObj.uid)
                callback(newFile)
            }
        } catch (e) {
            console.log('压缩失败')
        }
    }

    convertBase64UrlToBlob(urlData) {
        const bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
        // 处理异常,将ascii码小于0的转换为大于0
        const ab = new ArrayBuffer(bytes.length)
        const ia = new Uint8Array(ab)
        for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i)
        }
        return new Blob([ab], {type: 'image/png'})
    }

    convertBase64UrlToFile(urlData, name, uid) {
        const bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
        // 处理异常,将ascii码小于0的转换为大于0
        const ab = new ArrayBuffer(bytes.length)
        const ia = new Uint8Array(ab)
        for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i)
        }
        var file = new File([ab], name, {type: 'image/png'})
        file.uid = uid;
        return file;
    }
}

module.exports = util
